package comp6231.project.replica.dimitri;
/**
 * Distributed Retail System
 * Oct 6, 2012 
 */


import java.io.RandomAccessFile;
import java.io.IOException;

/**
 * @author dimitri.tiago
 *
 */
public class RandomAccessCustomerRecord extends CustomerRecord
{
	public static final int SIZE = 18;	// record size in bytes (String, int, int)

	public RandomAccessCustomerRecord()
	{
		this("", 0, 0);
	}

	public RandomAccessCustomerRecord(String customerID, int itemID, int numberOfItems)
	{
		super(customerID, itemID, numberOfItems);
	}

	public void read(RandomAccessFile file) throws IOException
	{
		setCustomerID(readCustomerID(file));
		setItemID(file.readInt());
		setNumberOfItems(file.readInt());
	}

	private String readCustomerID(RandomAccessFile file) throws IOException
	{
		char customerID [] = new char[6];
		char temp;

		// read customer id from file
		for (int i = 0; i < customerID.length; i++)
		{
			temp = file.readChar();
			customerID[i] = temp;
		}

		return new String(customerID).replace('\0', ' ');
	}

	public void write(RandomAccessFile file)
	{
		try
		{
			writeCustomerID(file, getCustomerID());
			file.writeInt(getItemID());
			file.writeInt(getNumberOfItems());
		} 
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	public void writeCustomerID(RandomAccessFile file, String customerID) throws IOException
	{
		StringBuffer buffer = null;

		if (customerID != null)
		{
			buffer = new StringBuffer(customerID);
		}
		else
		{
			buffer = new StringBuffer(6);
		}

		buffer.setLength(6);
		file.writeChars(buffer.toString());
	}
}
